import flet as ft
from views.borrow import BorrowPage
#from views.layout import main_view
from views.lend import LendPage
from views.query import QueryPage
from views.settings import SettingsPage


def main(page: ft.Page):
	page.title = "设备借还管理系统"
	page.theme_mode = ft.ThemeMode.LIGHT
	# 初始化数据库
	from models.device import DeviceRecord
	from models.database import DatabaseHelper
	db = DatabaseHelper()
	db.execute(DeviceRecord.create_table())
	
	# 导航栏控件
	nav_bar = ft.NavigationRail(
		label_type=ft.NavigationRailLabelType.ALL,
		destinations=[
			ft.NavigationRailDestination(icon=ft.icons.LIST, label="借出"),
			ft.NavigationRailDestination(icon=ft.icons.INPUT, label="借入"),
			ft.NavigationRailDestination(icon=ft.icons.SEARCH, label="查询"),
			ft.NavigationRailDestination(icon=ft.icons.SETTINGS, label="设置"),
		],
		on_change=lambda e: page.go(f"/{e.control.destinations[e.control.selected_index].label}"),
		selected_index=0
	)
	
	# 路由配置
	def route_change(e):
		page.views.clear()
		route_map = {
			"/借出": (BorrowPage, 0),
			"/借入": (LendPage, 1),
			"/查询": (QueryPage, 2),
			"/设置": (SettingsPage, 3)
		}
		
		if page.route in route_map:
			page_class, index = route_map[page.route]
			nav_bar.selected_index = index
			view = page_class(page).view
		else:
			view = ft.Text("页面不存在", size=30)
		
		page.views.append(
			ft.View(
				route=page.route,
				controls=[
					ft.Row(
						[
							nav_bar,
							ft.VerticalDivider(width=1),
							ft.Column([view], expand=True)
						],
						expand=True  # 父容器也需要设置expand
					)
				],
				padding=0
			)
		)
		page.update()
	
	page.on_route_change = route_change
	page.go("/借出")
	
	# 加载主界面
	#page.add(main_view(db, page))
ft.app(target=main)
